<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="en">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="Hero's notebooks" type="application/atom+xml">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="hero&apos;s notebooks">
<meta property="og:type" content="website">
<meta property="og:title" content="Hero&#39;s notebooks">
<meta property="og:url" content="https://chenzk1.github.io/page/3/index.html">
<meta property="og:site_name" content="Hero&#39;s notebooks">
<meta property="og:description" content="hero&apos;s notebooks">
<meta property="og:locale" content="en">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hero&#39;s notebooks">
<meta name="twitter:description" content="hero&apos;s notebooks">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenzk1.github.io/page/3/">





  <title>Hero's notebooks</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hero's notebooks</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Sometimes naive.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/07/03/RF、GBDT、XGBoost/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/07/03/RF、GBDT、XGBoost/" itemprop="url">RF & GBDT & XGBoost面试题目</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-03T08:52:13+08:00">
                2019-07-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="RF与GBDT之间的区别"><a href="#RF与GBDT之间的区别" class="headerlink" title="RF与GBDT之间的区别"></a>RF与GBDT之间的区别</h1><h2 id="相同点"><a href="#相同点" class="headerlink" title="相同点"></a>相同点</h2><ul>
<li>都是由多棵树组成</li>
<li>最终的结果都是由多棵树一起决定</li>
</ul>
<h2 id="不同点"><a href="#不同点" class="headerlink" title="不同点"></a>不同点</h2><ul>
<li>组成随机森林的树可以分类树也可以是回归树，而GBDT只由回归树组成</li>
<li>组成随机森林的树可以并行生成，而GBDT是串行生成</li>
<li>随机森林的结果是多数表决表决的，而GBDT则是多棵树累加之和</li>
<li>随机森林对异常值不敏感，而GBDT对异常值比较敏感</li>
<li>随机森林是通过减少模型的方差来提高性能，而GBDT是减少模型的偏差来提高性能的</li>
<li>随机森林不需要进行数据预处理，即特征归一化。而GBDT则需要进行特征归一化</li>
</ul>
<h3 id="分类树和回归树的区别"><a href="#分类树和回归树的区别" class="headerlink" title="分类树和回归树的区别"></a>分类树和回归树的区别</h3><ul>
<li>回归树和分类树的区别在于样本输出，如果样本输出是离散值，那么这是一颗分类树。如果果样本输出是连续值，那么那么这是一颗回归树。</li>
<li>分类树使用信息增益或增益比率来划分节点；每个节点样本的类别情况投票决定测试样本的类别。</li>
<li>回归树使用最小化均方差划分节点；每个节点样本的均值作为测试样本的回归预测值</li>
</ul>
<h1 id="Xgboost和GBDT的区别"><a href="#Xgboost和GBDT的区别" class="headerlink" title="Xgboost和GBDT的区别"></a>Xgboost和GBDT的区别</h1><ul>
<li>传统GBDT以CART作为基分类器，xgboost还支持线性分类器，这个时候xgboost相当于带L1和L2正则化项的逻辑斯蒂回归（分类问题）或者线性回归（回归问题）。</li>
<li>节点分裂的方式不同，gbdt是用的gini系数，xgboost是经过优化推导后的。</li>
<li>Xgboost在代价函数里加入了正则项，用于控制模型的复杂度，降低了过拟合的可能性。正则项里包含了树的叶子节点个数、每个叶子节点上输出的score的L2模的平方和。</li>
<li>shrinkage（缩减），相当于学习速率（XGBoost中的eta）。XGBoost在进行完一次迭代时，会将叶子节点的权值乘上该系数，主要是为了削弱每棵树的影响，让后面有更大的学习空间。（GBDT也有学习速率）</li>
<li>列采样</li>
<li><p>传统GBDT在优化时只用到一阶导数信息，xgboost则对代价函数进行了二阶泰勒展开，同时用到了一阶和二阶导数。</p>
<ul>
<li>为什么xgboost要用泰勒展开，优势在哪里？xgboost使用了一阶和二阶偏导, 二阶导数有利于梯度下降的更快更准. 使用泰勒展开取得函数做自变量的二阶导数形式, 可以在不选定损失函数具体形式的情况下, 仅仅依靠输入数据的值就可以进行叶子分裂优化计算, 本质上也就把损失函数的选取和模型算法优化/参数选择分开了. 这种去耦合增加了xgboost的适用性, 使得它按需选取损失函数, 可以用于分类, 也可以用于回归。</li>
</ul>
</li>
<li><p>Xgboost工具支持并行。boosting不是一种串行的结构吗?怎么并行的？注意xgboost的并行<strong>不是tree粒度的并行</strong>，xgboost也是一次迭代完才能进行下一次迭代的（第t次迭代的代价函数里包含了前面t-1次迭代的预测值）。<strong>xgboost的并行是在特征粒度上的</strong>。我们知道，决策树的学习最耗时的一个步骤就是对特征的值进行排序（因为要确定最佳分割点），xgboost在训练之前，<strong>预先对数据进行了排序</strong>，然后保存为block结构，后面的迭代中重复地使用这个结构，大大减小计算量。这个block结构也使得并行成为了可能，在进行节点的分裂时，需要计算每个特征的增益，最终选增益最大的那个特征去做分裂，那么各个特征的增益计算就可以开多线程进行</p>
</li>
</ul>
<h2 id="N问GBDT"><a href="#N问GBDT" class="headerlink" title="N问GBDT"></a>N问GBDT</h2><ul>
<li>GBDT的核心就在于，每一棵树学的是之前所有树结论和的残差，这个残差就是一个加预测值后能得真实值的累加量</li>
<li>怎样设置单棵树的停止生长条件？<ul>
<li>A. 节点分裂时的最小样本数</li>
<li>B. 最大深度</li>
<li>C. 最多叶子节点数</li>
<li>D. loss满足约束条件</li>
</ul>
</li>
<li>如何评估特征的权重大小？<ul>
<li>A. 通过计算每个特征在训练集下的信息增益，最后计算每个特征信息增益与所有特征信息增益之和的比例为权重值。</li>
<li>B. 借鉴投票机制。用相同的gbdt参数对w每个特征训练出一个模型，然后在该模型下计算每个特征正确分类的个数，最后计算每个特征正确分类的个数与所有正确分类个数之和的比例为权重值。</li>
</ul>
</li>
<li>当增加样本数量时，训练时长是线性增加吗？<ul>
<li>不是。因为生成单棵决策树时，损失函数极小值与样本数量N不是线性相关</li>
</ul>
</li>
<li>当增加树的棵数时，训练时长是线性增加吗？<ul>
<li>不是。因为每棵树的生成的时间复杂度不一样。</li>
</ul>
</li>
<li>当增加一个棵树叶子节点数目时，训练时长是线性增加吗？<ul>
<li>不是。叶子节点数和每棵树的生成的时间复杂度不成正比。</li>
</ul>
</li>
<li>每个节点上都保存什么信息？<ul>
<li>中间节点保存某个特征的分割值，叶结点保存预测是某个类别的概率。</li>
</ul>
</li>
<li>如何防止过拟合？<ul>
<li>a. 增加样本（data bias or small data的缘故），移除噪声。</li>
<li>b. 减少特征，保留重要的特征（可以用PCA等对特征进行降维）。</li>
<li>c. 对样本进行采样（类似bagging）。就是建树的时候，不是把所有的样本都作为输入，而是选择一个子集。</li>
<li>d. 对特征进行采样。类似样本采样一样, 每次建树的时候，只对部分的特征进行切分。</li>
</ul>
</li>
<li>gbdt在训练和预测的时候都用到了步长，这两个步长一样么？都有什么用，如果不一样，为什么？怎么设步长的大小？（太小？太大？）在预测时，设太大对排序结果有什么影响？跟shrinking里面的步长一样么这两个步长一样么？<ul>
<li>训练跟预测时，两个步长是一样的，也就是预测时的步长为训练时的步长，从训练的过程可以得知（更新当前迭代模型的时候）。</li>
<li>都有什么用，如果不一样，为什么？答：它的作用就是使得每次更新模型的时候，使得loss能够平稳地沿着负梯度的方向下降，不至于发生震荡。</li>
<li>那么怎么设步长的大小?<ul>
<li>有两种方法，一种就是按策略来决定步长，另一种就是在训练模型的同时，学习步长。</li>
<li>策略：a.每个树步长恒定且相等，一般设较小的值；b.开始的时候给步长设一个较小值，随着迭代次数动态改变，或者说衰减。</li>
<li>学习：因为在训练第k棵树的时候，前k-1棵树时已知的，而且求梯度的时候是利用前k-1棵树来获得。所以这个时候，就可以把步长当作一个变量来学习。</li>
</ul>
</li>
<li>（太小？太大？）在预测时，对排序结果有什么影响？<ul>
<li>如果步长过大，在训练的时候容易发生震荡，使得模型学不好，或者完全没有学好，从而导致模型精度不好。</li>
<li>而步长过小，导致训练时间过长，即迭代次数较大，从而生成较多的树，使得模型变得复杂，容易造成过拟合以及增加计算量。</li>
</ul>
</li>
<li>跟shrinking里面的步长一样么？<ul>
<li>这里的步长跟shrinking里面的步长是一致的。</li>
</ul>
</li>
</ul>
</li>
<li>boosting的本意是是什么？跟bagging，random forest，adaboost，gradient boosting有什么区别？<ul>
<li>Bagging<ul>
<li>放回抽样，多数表决（分类）或简单平均（回归）</li>
<li>可以看成是一种圆桌会议，或是投票选举的形式。通过训练多个模型，将这些训练好的模型进行加权组合来获得最终的输出结果(分类/回归)，一般这类方法的效果，都会好于单个模型的效果。在实践中，在特征一定的情况下，大家总是使用Bagging的思想去提升效果。例如kaggle上的问题解决，因为大家获得的数据都是一样的，特别是有些数据已经过预处理。</li>
<li>基本的思路：训练时，使用replacement的sampling方法，sampling一部分训练数据k次并训练k个模型；预测时，使用k个模型，如果为分类，则让k个模型均进行分类并选择出现次数最多的类（每个类出现的次数占比可以视为置信度）；如为回归，则为各分类器返回的结果的平均值。在该处，Bagging算法可以认为每个分类器的权重都一样由于每次迭代的采样是独立的，所以bagging可以并行。</li>
</ul>
</li>
<li>Random forest<ul>
<li>随机森林在bagging的基础上做了修改。<ul>
<li>A. 从样本集散用Boostrap采样选出n个样本，预建立CART</li>
<li>B. 在树的每个节点上，从所有属性中随机选择k个属性/特征，选择出一个最佳属性/特征作为节点</li>
<li>C. 重复上述两步m次，i.e.build m棵cart</li>
<li>D. 这m棵cart形成random forest。</li>
</ul>
</li>
<li>随机森林可以既处理属性是离散的量，比如ID3算法，也可以处理属性为连续值得量，比如C4.5算法。这里的random就是指：<ul>
<li>A. boostrap中的随机选择样本</li>
<li>B. random subspace的算法中从属性/特征即中随机选择k个属性/特征，每棵树节点分裂时，从这随机的k个属性/特征，选择最优的。</li>
</ul>
</li>
</ul>
</li>
<li>Boosting:<ul>
<li>一般Boosting算法都是一个迭代的过程，每一次新的训练都是为了改进上一次的结果。</li>
<li>boosting的采样或者更改样本的权重依赖于上一次迭代的结果，在迭代层面上是不能并行的。</li>
<li>boosting在选择hyperspace的时候给样本加了一个权值，使得loss function尽量考虑那些分错类的样本（如分错类的样本weight大）。怎么做的呢？<ul>
<li>boosting重采样的不是样本，而是样本的分布，对于分类正确的样本权值低，分类错误的样本权值高(通常是边界附近的样本)，最后的分类器是很多弱分类器的线性叠加(加权组合)。</li>
</ul>
</li>
</ul>
</li>
<li>Adaboosting<ul>
<li>对一份数据，建立M个模型(比如分类)，而一般这种模型比较简单，称为弱分类器(weak learner)。每次分类都将上一次分错的数据权重提高一点，对分对的数据权重降低一点，再进行分类。这样最终得到的分类器在测试数据与训练数据上都可以得到比较好的效果。</li>
<li>每次迭代的样本是一样的，即没有采样过程，不同的是不同的样本权重不一样。(当然也可以对样本/特征进行采样，这个不是adaboosting的原意)。</li>
<li>另外，每个分类器的步长由在训练该分类器时的误差来生成。</li>
</ul>
</li>
<li>Gradient boosting<ul>
<li>每一次的计算是为了减少上一次的残差(residual)，而为了消除残差，我们可以在残差减少的梯度 (Gradient)方向上建立一个新的模型。所以说在Gradient Boost中，每个新模型是为了使之前模型的残差往梯度方向减少，与传统Boost对正确，错误的样本进行加权有着很大的区别。</li>
</ul>
</li>
</ul>
</li>
<li>gbdt中哪些部分可以并行？<ul>
<li>A. 计算每个样本的负梯度</li>
<li>B. 分裂挑选最佳特征及其分割点时，对特征计算相应的误差及均值时</li>
<li>C. 更新每个样本的负梯度时</li>
<li>D. 最后预测过程中，每个样本将之前的所有树的结果累加的时候</li>
</ul>
</li>
<li>树生长成畸形树，会带来哪些危害，如何预防？<ul>
<li>在生成树的过程中，加入树不平衡的约束条件。这种约束条件可以是用户自定义的。例如对样本集中分到某个节点，而另一个节点的样本很少的情况进行惩罚。</li>
</ul>
</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/07/02/树的遍历/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/07/02/树的遍历/" itemprop="url">树的遍历</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-02T22:03:38+08:00">
                2019-07-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <ul>
<li>树的遍历，分深度优先：前序，中序，后序；广度优先：层次遍历。</li>
<li>前序：根、左、右</li>
<li>中序：左、根、右</li>
<li>后序：左、右、根</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""节点类"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, elem=<span class="number">-1</span>, lchild=None, rchild=None)</span>:</span></span><br><span class="line">        self.elem = elem</span><br><span class="line">        self.lchild = lchild</span><br><span class="line">        self.rchild = rchild</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tree</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""树类"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.root = Node()</span><br><span class="line">        self.myQueue = []</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(self, elem)</span>:</span></span><br><span class="line">        <span class="string">"""为树添加节点"""</span></span><br><span class="line">        node = Node(elem)</span><br><span class="line">        <span class="keyword">if</span> self.root.elem == <span class="number">-1</span>:  <span class="comment"># 如果树是空的，则对根节点赋值</span></span><br><span class="line">            self.root = node</span><br><span class="line">            self.myQueue.append(self.root)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            treeNode = self.myQueue[<span class="number">0</span>]  <span class="comment"># 此结点的子树还没有齐。</span></span><br><span class="line">            <span class="keyword">if</span> treeNode.lchild == <span class="literal">None</span>:</span><br><span class="line">                treeNode.lchild = node</span><br><span class="line">                self.myQueue.append(treeNode.lchild)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                treeNode.rchild = node</span><br><span class="line">                self.myQueue.append(treeNode.rchild)</span><br><span class="line">                self.myQueue.pop(<span class="number">0</span>)  <span class="comment"># 如果该结点已经有了右子树，将此结点丢弃，从下一个节点插入。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">front_digui</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用递归实现树的先序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">print</span> root.elem,</span><br><span class="line">        self.front_digui(root.lchild)</span><br><span class="line">        self.front_digui(root.rchild)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">middle_digui</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用递归实现树的中序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.middle_digui(root.lchild)</span><br><span class="line">        <span class="keyword">print</span> root.elem,</span><br><span class="line">        self.middle_digui(root.rchild)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">later_digui</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用递归实现树的后序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.later_digui(root.lchild)</span><br><span class="line">        self.later_digui(root.rchild)</span><br><span class="line">        <span class="keyword">print</span> root.elem,</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">front_stack</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用堆栈实现树的先序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        myStack = []</span><br><span class="line">        node = root</span><br><span class="line">        <span class="keyword">while</span> node <span class="keyword">or</span> myStack:</span><br><span class="line">            <span class="keyword">while</span> node:                     <span class="comment">#从根节点开始，一直找它的左子树</span></span><br><span class="line">                <span class="keyword">print</span> node.elem,</span><br><span class="line">                myStack.append(node)</span><br><span class="line">                node = node.lchild</span><br><span class="line">            node = myStack.pop()            <span class="comment">#while结束表示当前节点node为空，即前一个节点没有左子树了</span></span><br><span class="line">            node = node.rchild                  <span class="comment">#开始查看它的右子树</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">middle_stack</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用堆栈实现树的中序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        myStack = []</span><br><span class="line">        node = root</span><br><span class="line">        <span class="keyword">while</span> node <span class="keyword">or</span> myStack:</span><br><span class="line">            <span class="keyword">while</span> node:                     <span class="comment">#从根节点开始，一直找它的左子树</span></span><br><span class="line">                myStack.append(node)</span><br><span class="line">                node = node.lchild</span><br><span class="line">            node = myStack.pop()            <span class="comment">#while结束表示当前节点node为空，即前一个节点没有左子树了</span></span><br><span class="line">            <span class="keyword">print</span> node.elem,</span><br><span class="line">            node = node.rchild                  <span class="comment">#开始查看它的右子树</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">later_stack</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用堆栈实现树的后序遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        myStack1 = []</span><br><span class="line">        myStack2 = []</span><br><span class="line">        node = root</span><br><span class="line">        myStack1.append(node)</span><br><span class="line">        <span class="keyword">while</span> myStack1:                   <span class="comment">#这个while循环的功能是找出后序遍历的逆序，存在myStack2里面</span></span><br><span class="line">            node = myStack1.pop()</span><br><span class="line">            <span class="keyword">if</span> node.lchild:</span><br><span class="line">                myStack1.append(node.lchild)</span><br><span class="line">            <span class="keyword">if</span> node.rchild:</span><br><span class="line">                myStack1.append(node.rchild)</span><br><span class="line">            myStack2.append(node)</span><br><span class="line">        <span class="keyword">while</span> myStack2:                         <span class="comment">#将myStack2中的元素出栈，即为后序遍历次序</span></span><br><span class="line">            <span class="keyword">print</span> myStack2.pop().elem,</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">level_queue</span><span class="params">(self, root)</span>:</span></span><br><span class="line">        <span class="string">"""利用队列实现树的层次遍历"""</span></span><br><span class="line">        <span class="keyword">if</span> root == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        myQueue = []</span><br><span class="line">        node = root</span><br><span class="line">        myQueue.append(node)</span><br><span class="line">        <span class="keyword">while</span> myQueue:</span><br><span class="line">            node = myQueue.pop(<span class="number">0</span>)</span><br><span class="line">            <span class="keyword">print</span> node.elem,</span><br><span class="line">            <span class="keyword">if</span> node.lchild != <span class="literal">None</span>:</span><br><span class="line">                myQueue.append(node.lchild)</span><br><span class="line">            <span class="keyword">if</span> node.rchild != <span class="literal">None</span>:</span><br><span class="line">                myQueue.append(node.rchild)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    <span class="string">"""主函数"""</span></span><br><span class="line">    elems = range(<span class="number">10</span>)           <span class="comment">#生成十个数据作为树节点</span></span><br><span class="line">    tree = Tree()          <span class="comment">#新建一个树对象</span></span><br><span class="line">    <span class="keyword">for</span> elem <span class="keyword">in</span> elems:                  </span><br><span class="line">        tree.add(elem)           <span class="comment">#逐个添加树的节点</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'队列实现层次遍历:'</span></span><br><span class="line">    tree.level_queue(tree.root)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n\n递归实现先序遍历:'</span></span><br><span class="line">    tree.front_digui(tree.root)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n递归实现中序遍历:'</span> </span><br><span class="line">    tree.middle_digui(tree.root)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n递归实现后序遍历:'</span></span><br><span class="line">    tree.later_digui(tree.root)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n\n堆栈实现先序遍历:'</span></span><br><span class="line">    tree.front_stack(tree.root)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n堆栈实现中序遍历:'</span></span><br><span class="line">    tree.middle_stack(tree.root)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'\n堆栈实现后序遍历:'</span></span><br><span class="line">    tree.later_stack(tree.root)</span><br></pre></td></tr></table></figure>
          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/07/02/实习面试真题整理及解答/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/07/02/实习面试真题整理及解答/" itemprop="url">实习面试真题整理及解答</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-02T20:52:25+08:00">
                2019-07-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="ML-DL"><a href="#ML-DL" class="headerlink" title="ML/DL"></a>ML/DL</h1><h2 id="过拟合、欠拟合"><a href="#过拟合、欠拟合" class="headerlink" title="过拟合、欠拟合"></a>过拟合、欠拟合</h2><ul>
<li>理解</li>
<li>过拟合<ul>
<li>增加样本（增加的样本分布要与原始样本的分布尽可能不同）</li>
<li>减少特征数量</li>
<li>正则化，例如l2正则化后，虽然参数数量没有变化，但是参数趋近于0，则特征的重要性减小了</li>
<li>样本采样</li>
<li>特征采样</li>
</ul>
</li>
</ul>
<h2 id="分类问题中正负例"><a href="#分类问题中正负例" class="headerlink" title="分类问题中正负例"></a>分类问题中正负例</h2><ul>
<li>过采样</li>
<li>降采样</li>
<li>AUC ROC</li>
<li>调整阈值</li>
</ul>
<h2 id="激活函数"><a href="#激活函数" class="headerlink" title="激活函数"></a>激活函数</h2><p>作用：本来是wx+b是线性的，加入非线性函数，使得理论上可以逼近所有函数。</p>
<ul>
<li>sigmoid f(x) = 1/(1+exp(-x))<ul>
<li>幂运算，计算量大</li>
<li>梯度消失与梯度爆炸：BP时每层都要求激活函数的导，这个导数如果小于1经过多次之后就会趋近于0，梯度消失；如果大于1，多次之后会非常大，梯度爆炸</li>
<li>其输出是非零均值的，例如某个神经元经过sigmoid之后的输出都大于0，此时输入到下一层后，因为wx+b，所以对w的导数为x，即导数大于0，导致的结果就是BP时w都正方向更新</li>
</ul>
</li>
<li>tanh f(x) = (1-exp(-2x)) / (1+exp(-2x))<ul>
<li>幂运算，计算量大</li>
<li>解决了非零均值的问题</li>
<li>梯度消失与梯度爆炸仍然存在</li>
</ul>
</li>
<li>ReLU f(x) = max(0,x)<ul>
<li>速度快（输出速度，收敛速度）</li>
<li>正区间解决了梯度消失问题</li>
<li>非零均值</li>
<li>Dead ReLU：某些神经元永远都不会被激活</li>
</ul>
</li>
<li>Leaky ReLU<ul>
<li>解决了Dead ReLU问题 </li>
</ul>
</li>
</ul>
<h2 id="Logistic-Regression"><a href="#Logistic-Regression" class="headerlink" title="Logistic Regression"></a>Logistic Regression</h2><ul>
<li>如何优化的？loss f 策略</li>
<li>如何避免过拟合<ul>
<li>增加样本（增加的样本分布要与原始样本的分布尽可能不同）</li>
<li>减少特征数量</li>
<li>正则化，例如l2正则化后，虽然参数数量没有变化，但是参数趋近于0，则特征的重要性减小了</li>
<li>每次迭代，调整学习速率</li>
</ul>
</li>
</ul>
<h2 id="线性模型解决非线性问题"><a href="#线性模型解决非线性问题" class="headerlink" title="线性模型解决非线性问题"></a>线性模型解决非线性问题</h2><ul>
<li>例如LR，SVM都是线性模型，但是使用非线性的核函数可以实现对非线性问题的解决</li>
</ul>
<h1 id="语言"><a href="#语言" class="headerlink" title="语言"></a>语言</h1><h2 id="python"><a href="#python" class="headerlink" title="python"></a>python</h2><ul>
<li>python数据类型：Numbers（数字）、String（字符串）、List（列表）、Tuple（元组）、Dictionary（字典）</li>
<li>元组和数组的差别：<ul>
<li>元组()不能修改，数组[]可以修改</li>
<li>字典{}，集合set()是无序的</li>
</ul>
</li>
</ul>
<h1 id="DS"><a href="#DS" class="headerlink" title="DS"></a>DS</h1><ul>
<li>二叉树的遍历</li>
<li><p>很大的一个文件寻找频率TOP-k的词</p>
</li>
<li><p>一个非递减序列，寻找某个数最后出现的位置</p>
</li>
<li><p>归并排序</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">merge_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> len(num) &lt;= <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    mid = num // <span class="number">2</span></span><br><span class="line">    left = merge_sort(num[:mid]) <span class="comment"># 从下往上的递归中，每次递归得到的left和right是排好序的，需要对两者合并后做排序</span></span><br><span class="line">    right = merge_sort(num[mid:])</span><br><span class="line">    <span class="keyword">return</span> merge_result(left, right)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">merge_result</span><span class="params">(left, right)</span>:</span></span><br><span class="line">    i,j = <span class="number">0</span>,<span class="number">0</span></span><br><span class="line">    result = []</span><br><span class="line">    <span class="keyword">while</span> i &lt; len(left) <span class="keyword">and</span> j &lt; len(right):</span><br><span class="line">        <span class="keyword">if</span> left[i] &lt;= right[j]:</span><br><span class="line">            result.append(left[i])</span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            result.append(right[j])</span><br><span class="line">            j += <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> result+left[i:]+right[j:]</span><br></pre></td></tr></table></figure>
</li>
<li><p>快排</p>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort1</span><span class="params">(num,left,right)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> left &gt;= right:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    low = left</span><br><span class="line">    high = right</span><br><span class="line">    pivot = num[left]</span><br><span class="line">    <span class="keyword">while</span> left &lt; right:</span><br><span class="line">        <span class="keyword">while</span> left &lt; right <span class="keyword">and</span> num[right] &gt; pivot:</span><br><span class="line">            right -= <span class="number">1</span></span><br><span class="line">        num[left] = num[right]</span><br><span class="line">        <span class="keyword">while</span> left &lt; right <span class="keyword">and</span> num[left] &lt;= pivot:</span><br><span class="line">            left += <span class="number">1</span></span><br><span class="line">        num[right] = num[left]</span><br><span class="line">    num[right] = pivot</span><br><span class="line">    quick_sort1(num, low, left<span class="number">-1</span>)</span><br><span class="line">    quick_sort1(num, right+<span class="number">1</span>, high)</span><br></pre></td></tr></table></figure>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort2</span><span class="params">(num,left,right)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> left &lt; right:</span><br><span class="line">        p = partition(num, left, right)</span><br><span class="line">        quick_sort2(num, left, p<span class="number">-1</span>)</span><br><span class="line">        quick_sort2(num, p+<span class="number">1</span>, right)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">partition</span><span class="params">(num, left, right)</span>:</span></span><br><span class="line">    pivot = num[right] <span class="comment"># 先挪左指针，用右边界作为pivot</span></span><br><span class="line">    i = left</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(left,right):</span><br><span class="line">        <span class="keyword">if</span> num[j] &lt;= pivot:</span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">            num[i], num[j] = num[j], num[i]</span><br><span class="line">    num[i+<span class="number">1</span>], num[right] = num[right], num[i+<span class="number">1</span>] <span class="comment"># 把基准数移过来</span></span><br><span class="line">    <span class="keyword">return</span> i+<span class="number">1</span></span><br></pre></td></tr></table></figure>
  <figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort3</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> len(num) &lt;= <span class="number">1</span>:</span><br><span class="line">    <span class="keyword">return</span> num</span><br><span class="line">    pivot = num[<span class="number">0</span>]</span><br><span class="line">    left = [num[i] <span class="keyword">for</span> i <span class="keyword">in</span> range(len(num)) <span class="keyword">if</span> num[i] &lt; pivot]</span><br><span class="line">    right = [num[i] <span class="keyword">for</span> i <span class="keyword">in</span> range(len(num)) <span class="keyword">if</span> num[i] &gt; pivot]</span><br><span class="line">    <span class="keyword">return</span> quick_sort3(left) + pivot + quick_sort3(right)</span><br></pre></td></tr></table></figure>
</li>
<li><p>O(N)复杂度在一个数组中寻找两数和为指定数的下标</p>
</li>
</ul>
<h1 id="逻辑"><a href="#逻辑" class="headerlink" title="逻辑"></a>逻辑</h1><ul>
<li>一个筛子产生0~9的随机数，要求概率相等</li>
<li>理发师数量估计</li>
</ul>
<h1 id="操作系统-计网"><a href="#操作系统-计网" class="headerlink" title="操作系统 + 计网"></a>操作系统 + 计网</h1><ul>
<li><p>进程和线程</p>
<p>进程和线程的主要差别在于它们是不同的操作系统资源管理方式。进程有独立的地址空间，一个进程崩溃后，在保护模式下不会对其它进程产生影响，而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量，但线程之间没有单独的地址空间，一个线程死掉就等于整个进程死掉，所以多进程的程序要比多线程的程序健壮，但在进程切换时，耗费资源较大，效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作，只能用线程，不能用进程。<br>1) 简而言之,一个程序至少有一个进程,一个进程至少有一个线程。<br>2) 线程的划分尺度小于进程，使得多线程程序的并发性高。<br>3) 进程在执行过程中拥有独立的内存单元，而多个线程共享内存，从而极大地提高了程序的运行效率。<br>4) 线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行，必须依存在应用程序中，由应用程序提供多个线程执行控制。<br>5) 从逻辑角度来看，多线程的意义在于一个应用程序中，有多个执行部分可以同时执行。但操作系统并没有将多个线程看做多个独立的应用，来实现进程的调度和管理以及资源分配。这就是进程和线程的重要区别。</p>
</li>
<li>同步和异步<ul>
<li>消息的通知机制</li>
<li>涉及到IO通知机制；所谓同步，就是发起调用后，被调用者处理消息，必须等处理完才直接返回结果，没处理完之前是不返回的，调用者主动等待结果；所谓异步，就是发起调用后，被调用者直接返回，但是并没有返回结果，等处理完消息后，通过状态、通知或者回调函数来通知调用者，调用者被动接收结果。</li>
</ul>
</li>
<li>阻塞和非阻塞<ul>
<li>程序等待调用结果时的状态</li>
<li>涉及到CPU线程调度；所谓阻塞，就是调用结果返回之前，该执行线程会被挂起，不释放CPU执行权，线程不能做其它事情，只能等待，只有等到调用结果返回了，才能接着往下执行；所谓非阻塞，就是在没有获取调用结果时，不是一直等待，线程可以往下执行，如果是同步的，通过轮询的方式检查有没有调用结果返回，如果是异步的，会通知回调。</li>
</ul>
</li>
<li>TCP和UDP<ul>
<li>基于连接（TCP）与无连接（UDP）； </li>
<li>对系统资源的要求（TCP较多，UDP少）； </li>
<li>UDP程序结构较简单； </li>
<li>流模式与数据报模式 ；</li>
<li>TCP保证数据正确性，UDP可能丢包，TCP保证数据顺序，UDP不保证。</li>
</ul>
</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/07/02/线性模型和非线性模型/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/07/02/线性模型和非线性模型/" itemprop="url">线性模型和非线性模型</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-02T15:56:00+08:00">
                2019-07-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <ol>
<li>判断非线性模型和线性模型：决策边界是否是直线 或 一个变量是否被一个参数所影响<br>（决策空间中，坐标是参数w，而原来的输入x，是该空间中的坐标点）</li>
</ol>
<ul>
<li>Logistic Regression是线性模型，本身是wx+b，每个变量都由一个参数决定，决策边界为wx+b &lt; c，决策面是wx+b=y,这是线性的，然后再把结果做了一个映射，映射到0~1，相当于分类的置信度。</li>
<li>神经网络则是典型的非线性网络，因为一个变量由多个参数决定，且参数之间有交互。</li>
<li>SVM，有线性和非线性版本。线性SVM，其模型本身就是在寻求一个超平面，只是策略是找到间隔最大的那个超平面。而非线性SVM，虽说在特征空间上仍是分类超平面，但是先采用了<strong>核技巧</strong>从输入空间向特征空间进行了非线性映射。</li>
<li>MLP，其嵌套函数的特点就反映了，它的非线性更像 LR ，即从每层来看，输入并没有进行 SVM 那样的非线性特征变换，但在输出时进行了非线性映射，那么多层重叠，也就实现了特征的非线性交叉。</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/07/02/排序算法python/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/07/02/排序算法python/" itemprop="url">十大排序算法python实现</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-02T08:54:51+08:00">
                2019-07-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <ul>
<li>下文中的稳定是指：若a=b，而排序后的ab顺序与原来的ab顺序一样</li>
<li>交换排序：冒泡、快排；<br>选择排序：选择、堆；<br>插入排序：插入、希尔；<br>归并排序、基数排序</li>
<li>总结：</li>
<li>排序算法 | 时间复杂度（平均） | 时间（最短） | 时间（最长） | 空间复杂度 | 是否稳定<br>— | — | — | — | — | —<br>冒泡 | O(N2) | O(N) | O(N2) | O(1) | 是<br>选择 | O(N2) | O(N2) | O(N2) | 0(1) | 否<br>插入 | O(N2) | O(N) | O(N2) | O(1) | 是<br>希尔 | O(n·log(n)2) | O(n3/2) | O(N2) | O(1) | 否<br>快速 | </li>
</ul>
<ol>
<li>冒泡排序</li>
</ol>
<ul>
<li>迭代n-1次，两个相邻元素两两相比，每次迭代将最大的元素放在该迭代序列的顶端。</li>
<li>优化后，对于最优的情况，即已经正序排列的，算法复杂度为O(N)<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bubble_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(num)<span class="number">-1</span>):</span><br><span class="line">        flag = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(len(num)-i<span class="number">-1</span>):</span><br><span class="line">            <span class="keyword">if</span> num[j] &gt; num[j+<span class="number">1</span>]:</span><br><span class="line">                num[j], num[j+<span class="number">1</span>] = num[j+<span class="number">1</span>], num[j]</span><br><span class="line">                flag = <span class="number">1</span></span><br><span class="line">        <span class="keyword">if</span> flag == <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">return</span> num</span><br><span class="line">    <span class="keyword">return</span> num</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ol start="2">
<li>选择排序</li>
</ol>
<ul>
<li>迭代n-1次，每次选择出最小的放到前面</li>
<li>不稳定，因为选择出最小的之后会跟原有数交换顺序，因此会破坏原来的顺序，例如5 3 5 2，第一次之后为2 3 5 5，此时5跟5的顺序变了</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">select_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(num)<span class="number">-1</span>):</span><br><span class="line">        min_index = i   </span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(i,len(num)<span class="number">-1</span>):</span><br><span class="line">            <span class="keyword">if</span> num[j+<span class="number">1</span>] &lt; num[min_index]:</span><br><span class="line">                min_index = j+<span class="number">1</span></span><br><span class="line">        num[i], num[min_index] = num[min_index], num[i]</span><br><span class="line">    <span class="keyword">return</span> num</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>插入排序</li>
</ol>
<ul>
<li>跟打牌类似</li>
<li>最快情况是O(N)，如果大部分数据已经排好序了，while pre_index &gt;= 0 and cur_num &lt; num[pre_index]这句的迭代次数会大大减少，会比较快</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">insert_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(num)<span class="number">-1</span>):</span><br><span class="line">        pre_index = i <span class="comment"># 前一个数</span></span><br><span class="line">        cur_num = num[i+<span class="number">1</span>] <span class="comment"># 当前待插入数 </span></span><br><span class="line">        <span class="keyword">while</span> pre_index &gt;= <span class="number">0</span> <span class="keyword">and</span> cur_num &lt; num[pre_index]:</span><br><span class="line">            num[pre_index+<span class="number">1</span>] = num[pre_index] <span class="comment"># 往后挪一位</span></span><br><span class="line">            pre_index -= <span class="number">1</span>   </span><br><span class="line">        num[pre_index+<span class="number">1</span>] = cur_num</span><br><span class="line">    <span class="keyword">return</span> num</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>希尔排序</li>
</ol>
<ul>
<li>对插入排序的优化，使用了递减的增量序列</li>
<li>如上所述插入排序中：如果大部分数据已经排好序了，while pre_index &gt;= 0 and cur_num &lt; num[pre_index]这句的迭代次数会大大减少，会比较快 –&gt; 所以希尔排序就是针对这个做了优化，即先减少需要排序的数量，再逐步对其排序</li>
<li>希尔排序是不稳定的算法，它满足稳定算法的定义。对于相同的两个数，可能由于分在不同的组中而导致它们的顺序发生变化。</li>
<li>希尔排序的性能根据其选取的序列而变化</li>
<li>使用动态增量序列的代码如下：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">shell_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    gap = <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> gap &lt; len(num) // <span class="number">3</span>: <span class="comment">#gap &lt; (3a,3a+1,3a+2)//3: (a-1)*3+1=3a-2</span></span><br><span class="line">        gap = gap*<span class="number">3</span> + <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> gap &gt; <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(gap,len(num)):</span><br><span class="line">            cur_num = num[gap]</span><br><span class="line">            pre_index = i-gap</span><br><span class="line">            <span class="keyword">while</span> pre_index &gt;= <span class="number">0</span> <span class="keyword">and</span> cur_num &lt; num[pre_index]:</span><br><span class="line">                num[pre_index+gap] = num[pre_index] </span><br><span class="line">                pre_index -= gap</span><br><span class="line">            num[pre_index+gap] = cur_num</span><br><span class="line">        gap //= <span class="number">3</span></span><br></pre></td></tr></table></figure>
<ol start="5">
<li>归并排序</li>
</ol>
<ul>
<li>递归</li>
<li>终止条件：剩一个元素时，返回该元素；再上一层对返回的两个元素比较排序</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">merge_sort</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">merge</span><span class="params">(left,right)</span>:</span> <span class="comment"># left和right本身是已经排序好的</span></span><br><span class="line">        result = []</span><br><span class="line">        i=j=<span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> i &lt; len(left) <span class="keyword">and</span> j &lt; len(right):</span><br><span class="line">            <span class="keyword">if</span> left[i] &lt;= right[j]:</span><br><span class="line">                result.append(left)</span><br><span class="line">                i+=<span class="number">1</span>            </span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                result.append(right)</span><br><span class="line">                j+=<span class="number">1</span></span><br><span class="line">        result = result + left[i:] + right[j:]</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> len(num) &lt;= <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    mid = len(num) // <span class="number">2</span></span><br><span class="line">    left = merge_sort(num[:mid])</span><br><span class="line">    right = merge_sort(num[mid:])</span><br><span class="line">    <span class="keyword">return</span> merge(left,right)</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>快速排序</li>
</ol>
<ul>
<li>冒泡+二分+递归分治</li>
<li>核心：每次迭代使选取的基准值插入到序列中，该序列中基准值左边的值小于基准值，右边的值大于基准值，然后再对两边分别迭代</li>
<li>基准数选择以及指针移动顺序：最终两个指针相遇时，要把基准数和相遇的位置交换，此时该位置左边的数小于基准数，右边大于基准数；若选择最左边的数为基准数，肯定要跟比它小的数交换，因此只有右指针先动才能找到比它小的（例如算法2里右指针相遇时找到的一定是上一轮左指针的交换结果，一定是小于基准数的）</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 二分之后不断地递归，每次递归求出基准值的具体位置</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort1</span><span class="params">(num)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> len(num) &lt;= <span class="number">1</span>:</span><br><span class="line">        <span class="keyword">return</span> num</span><br><span class="line">    pivot = num[<span class="number">0</span>]</span><br><span class="line">    left = [num[i] <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>,len(num)) <span class="keyword">if</span> num[i] &lt;= pivot]</span><br><span class="line">    right = [num[i] <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>,len(num)) <span class="keyword">if</span> num[i] &gt; pivot]</span><br><span class="line">    <span class="keyword">return</span> quick_sort1(left) + pivot + quick_sort2(right)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort2</span><span class="params">(num,left,right)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> left &gt;= right: <span class="comment"># 两指针相遇，则终止</span></span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    low = left</span><br><span class="line">    high = right</span><br><span class="line">    pivot = num[left]</span><br><span class="line">    <span class="keyword">while</span> left &lt; right:</span><br><span class="line">        <span class="keyword">while</span> left &lt; right <span class="keyword">and</span> num[right] &gt; pivot: <span class="comment"># 右指针向左移动直到找到小于pivot的</span></span><br><span class="line">            right -= <span class="number">1</span></span><br><span class="line">        num[left] = num[right] <span class="comment"># 右边有小于基准值的，调整到左边</span></span><br><span class="line">        <span class="keyword">while</span> left &lt; right <span class="keyword">and</span> num[left] &lt;= pivot: <span class="comment"># 右指针向左移动直到找到小于pivot的</span></span><br><span class="line">            left += <span class="number">1</span></span><br><span class="line">        num[right] = num[left] <span class="comment"># 左边有小于基准值的，调整到右边</span></span><br><span class="line">    num[right] = pivot </span><br><span class="line">    quick_sort2(num, low, left<span class="number">-1</span>)</span><br><span class="line">    quick_sort2(num, right+<span class="number">1</span>, high)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">quick_sort3</span><span class="params">(num,left,right)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> left &lt; right:</span><br><span class="line">        p = partition(num, left, right)</span><br><span class="line">        quick_sort3(num, left, p<span class="number">-1</span>)</span><br><span class="line">        quick_sort3(num, p+<span class="number">1</span>, right)</span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">partition</span><span class="params">(num, left, right)</span>:</span></span><br><span class="line">    pivot = num[right] <span class="comment"># 这里是从左边开始移动指针的，因此是right</span></span><br><span class="line">    i = left - <span class="number">1</span></span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(left, right):</span><br><span class="line">        <span class="keyword">if</span> num[j] &lt;= pivot:</span><br><span class="line">            i += <span class="number">1</span></span><br><span class="line">            num[i], num[j] = num[j], num[i]</span><br><span class="line">    num[i+<span class="number">1</span>], num[right] = num[right], num[i+<span class="number">1</span>] <span class="comment"># 把基准数移过来</span></span><br><span class="line">    <span class="keyword">return</span> i+<span class="number">1</span></span><br></pre></td></tr></table></figure>
          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/06/19/logstic regression, softmax regression/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/06/19/logstic regression, softmax regression/" itemprop="url">logistic regression, softmax regression</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-06-19T15:59:42+08:00">
                2019-06-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p><a href="https://blog.csdn.net/google19890102/article/details/41594889" target="_blank" rel="noopener">post</a></p>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/05/27/信息熵、交叉熵、条件熵、互信息/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/05/27/信息熵、交叉熵、条件熵、互信息/" itemprop="url">信息熵、交叉熵、条件熵、相对熵(K-L散度)、互信息</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-05-27T08:17:35+08:00">
                2019-05-27
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <ul>
<li>设随机变量X，有n个事件$x_i$ –&gt; $x_n$，概率分布为p(x)</li>
</ul>
<ol>
<li><p>信息</p>
<ul>
<li>某随机变量X取值为xi的信息为 $I(X=xi)=\log_2\frac{1}{p(x_i)}=-\log_2p(x_i)$<br>：某事件xi的信息代表这个事件能提供的信息，一个发生概率越小的事件能够提供的信息量越大。</li>
</ul>
</li>
<li><p>信息熵</p>
<ul>
<li>信息代表一个事件的不确定性，信息熵是整个随机变量X不确定性的度量：<strong>信息的期望</strong>。<br>$H(X)=\sum_0^np(x_i)*I(x_i)=-\sum_0^np(x_i)\log_2(p(x_i))$</li>
<li>信息熵只与变量X的分布有关，与其取值无关。例如二分类中，两取值的概率均为0.5时，其熵最大，也最难预测某时刻哪一类别会发生。</li>
<li>如何通俗的解释交叉熵与相对熵? - CyberRep的回答 - 知乎<br><a href="https://www.zhihu.com/question/41252833/answer/195901726" target="_blank" rel="noopener">https://www.zhihu.com/question/41252833/answer/195901726</a></li>
<li>对于一个系统而言，若获知其真实分布，则我们能够找到一个最优策略，以最小的代价来消除系统的不确定性，而这个最小的代价（猜题次数、编码长度等）就是信息熵。</li>
</ul>
</li>
<li><p>条件熵</p>
<ul>
<li>定义为：给定条件X下，Y的分布（Y|X）的熵对X的数学期望：$H(Y|X)=\sum_xp(x)H(Y|X=x)$</li>
<li>在ML中，即选定某个特征X(X有n类)后，label(Y)的条件概率熵求期望：<strong>给定X特征的条件下Y的信息熵</strong>。</li>
<li>条件熵越小，代表在这个特征下，label的信息熵越小，也就是说要解决问题的代价越小。</li>
</ul>
</li>
<li><p>信息增益 — ID3</p>
<ul>
<li>$IG(Y|X)=H(Y)-H(Y|X)$</li>
<li>在决策树中作为选择特征的指标，IG越大，这个特征的选择性越好，也可以理解为：待分类的集合的熵和选定某个特征的条件熵之差越大，这个特征对整个集合的影响越大。</li>
<li>对于条件熵来说，条件熵越小，分类后的纯度越高，但是问题是：X的取值越多，每个取值下Y的纯度越高，H(Y|X)越小，但此时并不有利于Y的区分。信息增益也是如此。–&gt; 信息增益率。</li>
</ul>
</li>
<li><p>信息增益率/信息增益比 — C4.5</p>
<ul>
<li>偏好取值少的特征。C4.5：先选择高于平均水平信息增益的特征，再在其中选择最高信息增益率的特征。</li>
<li>见<a href="https://chenzk1.github.io/2019/03/14/Decision%20Tree/">Decision Tree</a></li>
</ul>
</li>
<li><p>基尼系数 — CART</p>
<ul>
<li><p>表示数据的不纯度。既有分类也有回归，既要确定特征，也要确定特征的分叉值。</p>
</li>
<li><p>见<a href="https://chenzk1.github.io/2019/03/14/Decision%20Tree/">Decision Tree</a></p>
</li>
</ul>
</li>
<li><p>交叉熵</p>
<ul>
<li>前面提到：信息熵是最优策略下，消除系统不确定性的最小代价。这里的前提是：<strong>我们得到了系统的真实分布</strong>。</li>
<li>实际中，一般难以获知系统真实分布，所以要以假设分布去近似。<strong>交叉熵：用来衡量在给定的真实分布下，使用非真实分布所指定的策略消除系统的不确定性所需要付出的努力的大小</strong>。$CEH(p,q)=\sum_{k=1}^np_k\log_2\frac{1}{q_k}$，注意这里log中是q，是基于非真实分布q的信息量对真实分布的期望。</li>
<li>当假设分布$q_k$与真实分布$p_k$相同时，交叉熵最低，等于信息熵，所以得到的策略为最优策略。<blockquote>
<p>在机器学习中的分类算法中，我们总是最小化交叉熵，因为交叉熵越低，就证明由算法所产生的策略最接近最优策略，也间接证明我们算法所算出的非真实分布越接近真实分布。</p>
</blockquote>
</li>
</ul>
<blockquote>
<p>例如：在逻辑斯蒂回归或者神经网络中都有用到交叉熵作为评价指标，其中p即为真实分布的概率，而q为预测的分布，以此衡量两不同<strong>分布</strong>的相似性。 </p>
<ul>
<li>如何衡量不同<strong>策略</strong>的差异：相对熵</li>
</ul>
</blockquote>
</li>
<li><p>相对熵/K-L散度</p>
<ul>
<li>用来衡量两个取值为正的函数或概率分布之间的差异。两者相同相对熵为0</li>
<li>使用非真实分布q的交叉熵，与使用真实分布p的的信息熵的差值：相对熵，又称K-L散度。</li>
<li>$KL(p,q)=CEH(p,q)-H(p)=\sum_{i=1}^np(x_i)\log\frac{p(x_i)}{q(x_i)}$</li>
</ul>
</li>
<li><p>联合熵</p>
<ul>
<li>H(X,Y) 随机变量X,Y联合表示的信息熵</li>
</ul>
</li>
<li><p>互信息</p>
<ul>
<li>H（X；Y）俩变量交集，也记作I(X;Y)</li>
<li>H（X；Y) = H(X,Y)-H(Y|X)-H(X|Y)</li>
<li>I(X;Y)=KL(P(X,Y), P(X)P(Y))</li>
</ul>
</li>
</ol>
<ul>
<li>互信息越小，两变量独立性越强，P(X,Y)与P(X)P(Y)差异越小，P(X,Y)与P(X)P(Y)的相对熵越小  </li>
<li>相对熵(p,q) = 信息熵(p) - 交叉熵(p,q)</li>
<li>信息增益(Y|X) = 信息熵(Y) - 条件熵(Y|X)</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/05/26/CTR/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/05/26/CTR/" itemprop="url">CTR_LR/Poly2/FM/FFM</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-05-26T20:57:46+08:00">
                2019-05-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <ol>
<li>LR</li>
</ol>
<ul>
<li>问题：特征之间无相关性</li>
</ul>
<ol start="2">
<li>Ploy2</li>
</ol>
<ul>
<li>暴力加入两两特征组合（权重*两特征点积）</li>
<li>问题：大部分特征是稀疏的，得到的特征值都是0，所以梯度更新时，因为大部分feature为0所以梯度并不会更新</li>
</ul>
<ol start="3">
<li>FM(Factorization Machine、因子机)</li>
</ol>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/04/11/Tips in DS Competition/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/04/11/Tips in DS Competition/" itemprop="url">Tips in DS Competition</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-04-11T20:30:34+08:00">
                2019-04-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h2 id="处理缺失数据"><a href="#处理缺失数据" class="headerlink" title="处理缺失数据"></a>处理缺失数据</h2><ul>
<li>删除</li>
<li>imputation: mean mode …</li>
<li>imputation + missing_flag</li>
<li>…</li>
</ul>
<h2 id="Categorial-Columns"><a href="#Categorial-Columns" class="headerlink" title="Categorial Columns"></a>Categorial Columns</h2><ul>
<li>对于种类不是很多的：onehot encoder<ul>
<li>sklearn.preprocessing.OneHotEncoder: 如果使用线性模型，存在一个问题就是生成的n列是线性相关的，因此要满足线性无关就要删除其中一列。该类提供了drop_first参数</li>
</ul>
</li>
<li>不用label encoder的原因：label encoder引入了大小顺序</li>
</ul>
<h2 id="XGBOOST"><a href="#XGBOOST" class="headerlink" title="XGBOOST"></a>XGBOOST</h2>
          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenzk1.github.io/2019/04/06/SVD&PCA/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Hero">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hero's notebooks">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                <a class="post-title-link" href="/2019/04/06/SVD&PCA/" itemprop="url">SVD&PCA</a></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-04-06T11:07:20+08:00">
                2019-04-06
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="特征值分解-Eigen-Value-Decomposition"><a href="#特征值分解-Eigen-Value-Decomposition" class="headerlink" title="特征值分解(Eigen Value Decomposition)"></a>特征值分解(Eigen Value Decomposition)</h3><p>Ax = λx</p>
<p>-&gt; A = WΣW^(-1)</p>
<p>其中Σ为对角阵，对角的值是A的特征值；W的列向量为对应的特征向量</p>
<p>对W标准化后，即Wi^(T).wi = 1</p>
<p>所以W^(T).W = I –&gt; W^(T) = W^(-1)</p>
<p><strong>W经标准化后为酉矩阵</strong></p>
<p>-&gt; A = WΣW^(T)</p>
<p><strong>!!A必须是方阵</strong></p>
<h3 id="SVD-Singular-Value-Decomposition"><a href="#SVD-Singular-Value-Decomposition" class="headerlink" title="SVD(Singular Value Decomposition)"></a>SVD(Singular Value Decomposition)</h3><ul>
<li>可以对<strong>非方阵</strong>分解</li>
<li>A = UΣV^(T), A: m x n, U: m x m, V: n x n, Σ: m x n; <strong>U和V都为酉矩阵</strong>，Σ主对角线上元素为奇异值</li>
<li>UVΣ的求解：<ul>
<li>U: AA^(T) = UΣ1U^(T)</li>
<li>V: A^(T)A = VΣ2V^(T)</li>
<li>Σ: A = UΣV^(T) =&gt; AV = UΣ =&gt; U^(T)AV = Σ =&gt; σi = Avi/ui</li>
</ul>
</li>
<li>性质：可以用几个最大的奇异值及其左右奇异向量近似原矩阵</li>
<li>应用：降维，数据压缩，去噪声；也可用于NLP，如LSA…</li>
</ul>
<h3 id="PCA"><a href="#PCA" class="headerlink" title="PCA"></a>PCA</h3><h4 id="基"><a href="#基" class="headerlink" title="基"></a>基</h4><p>由线性不相关的向量组成，有时会取正交。</p>
<h4 id="坐标变换-amp-矩阵相乘"><a href="#坐标变换-amp-矩阵相乘" class="headerlink" title="坐标变换&amp;矩阵相乘"></a>坐标变换&amp;矩阵相乘</h4><p>AB = C，B矩阵的每一个列向量变换到以A矩阵的行向量为基表示的空间中，最终得到的向量的维度（C的行数）取决于基的个数 –&gt; 可用于降、升维</p>
<h4 id="降维"><a href="#降维" class="headerlink" title="降维"></a>降维</h4><ul>
<li>降维的目标：维数变低&amp;尽量保留更多的信息。</li>
<li>对于二维降到一维，要保留更多的信息，则原始向量在基向量上的投影应相隔距离尽量远 –&gt; 大方差</li>
<li><p>对于高维数据，如3维到2维，若只遵循大方差的原则，则两个基向量会相隔很近 –&gt; 信息不够分散 –&gt; 基向量之间的相关系数应尽量小</p>
</li>
<li><p>方差：单个随机变量之间的离散程度；协方差：多个随机变量之间的相似性</p>
</li>
</ul>
<p><strong>综上 –&gt; 协方差矩阵</strong></p>
<h4 id="协方差矩阵"><a href="#协方差矩阵" class="headerlink" title="协方差矩阵"></a>协方差矩阵</h4><p>协方差矩阵对角线上是原矩阵的方差，其他位置的元素是原矩阵两两向量之间的协方差 –&gt; 协方差矩阵是实对称矩阵 –&gt; 可逆</p>
<ul>
<li>原始问题即协方差矩阵的对角化</li>
</ul>
<h4 id="协方差矩阵对角化"><a href="#协方差矩阵对角化" class="headerlink" title="协方差矩阵对角化"></a>协方差矩阵对角化</h4><ul>
<li>原向量X，对应的协方差矩阵为C，P为基向量组成的变换矩阵；X经变换后为Y，Y=PX，Y的协方差矩阵为D，则：设X Y的期望为0，<br>D = YY^(T) / m = PX X^(T)P^(T) / m = PCP^(T)</li>
<li>PCA即寻找矩阵P使得 PCP^(T)是一个对角矩阵，且对角线上的值从大到小排列，取前k个值，以及对应P中的k个向量，即可将原n维矩阵降维至k维 –&gt; D对角线上的值即特征值，P为特征向量组成的矩阵</li>
</ul>
<h4 id="PCA-1"><a href="#PCA-1" class="headerlink" title="PCA"></a>PCA</h4><ul>
<li>总结：寻找实现协方差矩阵对角化的矩阵P，并应用P对原有数据进行变换</li>
<li>算法步骤<br>设有m条n维数据：</li>
</ul>
<ol>
<li>将原始数据按列组成n行m列矩阵X</li>
<li>将X的每一行（代表一个属性字段）进行零均值化，即减去这一行的均值</li>
<li>求出协方差矩阵C = XX^(T) / m</li>
<li>求出协方差矩阵的特征值及对应的特征向量</li>
<li>将特征向量按对应特征值大小从上到下按行排列成矩阵，取前k行组成矩阵P</li>
<li>Y=PX即为降维到k维后的数据</li>
</ol>
<ul>
<li>优点：降低数据特征维度，减少数据存储量；加快运行速度</li>
<li>注意事项：<strong>量纲敏感性</strong>，最好进行量纲统一化；适用于大样本，小样本的话建议因子分析法</li>
</ul>

          
        
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/2/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><a class="page-number" href="/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/page/4/">4</a><a class="page-number" href="/page/5/">5</a><a class="extend next" rel="next" href="/page/4/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Hero">
          <p class="site-author-name" itemprop="name">Hero</p>
           
              <p class="site-description motion-element" itemprop="description">hero's notebooks</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">47</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Hero</span>
</div>


<div class="powered-by">
  Powered by <a class="theme-link" href="https://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
    <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>

  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
